package com.lw.leetcode.tree.c;

import com.lw.leetcode.tree.TreeNode;

/**
 * 剑指 Offer 37. 序列化二叉树
 * 297. 二叉树的序列化与反序列化
 * 剑指 Offer II 048. 序列化与反序列化二叉树
 * 449. 序列化和反序列化二叉搜索树
 *
 * @Author liw
 * @Date 2021/6/30 9:22
 * @Version 1.0
 */
public class Codec {

    public static void main(String[] args) {
        Codec test = new Codec();
        TreeNode instance4 = TreeNode.getInstance4();

        String str = test.serialize(instance4);
        System.out.println(str);
        TreeNode deserialize = test.deserialize(str);
        System.out.println(deserialize);

    }


    private int index = 0;
    private String[] strs;

    public String serialize(TreeNode root) {
        StringBuilder res = new StringBuilder();
        node2Str(root, res);
        return res.toString();
    }

    public TreeNode deserialize(String data) {
        strs = data.split(",");
        index = 0;
        return str2Node();
    }

    private void node2Str(TreeNode root, StringBuilder str) {
        if (null == root) {
            str.append("null,");
            return;
        }
        str.append(root.val);
        str.append(",");
        node2Str(root.left, str);
        node2Str(root.right, str);
    }

    private TreeNode str2Node() {
        if ("null".equals(strs[index])) {
            index++;
            return null;
        }
        TreeNode res = new TreeNode(Integer.valueOf(strs[index]));
        index++;
        res.left = str2Node();
        res.right = str2Node();
        return res;
    }

}
